package com.jnevision.replacecard.controller;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.api.ApiController;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jnevision.clockin.model.ClockIn;
import com.jnevision.clockin.service.ClockInServiceImpl;
import com.jnevision.common.CommonQuery;
import com.jnevision.replacecard.model.ReplaceCard;
import com.jnevision.replacecard.model.ReplaceCardVO;
import com.jnevision.replacecard.service.ReplaceCardServiceImpl;
import com.jnevision.replacecardapprovalrecords.model.ReplaceCardApprovalRecords;
import com.jnevision.replacecardapprovalrecords.service.ReplaceCardApprovalRecordsServiceImpl;
import com.jnevision.user.model.User;
import com.jnevision.user.service.UserServiceImpl;
import com.jnevision.util.JsonMapper;

/**
 * <p>
 * 补卡申请 前端控制器
 * </p>
 *
 * @author gavin
 * @since 2019-07-15
 */

@RestController
@RequestMapping("/replacecards")
public class ReplaceCardController extends ApiController {
    @Autowired
    private ReplaceCardServiceImpl replaceCardServiceImpl;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private ReplaceCardApprovalRecordsServiceImpl replaceCardApprovalRecordsServiceImpl;
    @Autowired
    private UserServiceImpl userServiceImpl;
    @Autowired
    private ClockInServiceImpl clockInServiceImpl;

    @PostMapping
    @Transactional
    public R<Boolean> add(@RequestBody ReplaceCard car, @RequestHeader(value = "token") String token) {
        User user = JsonMapper.nonDefaultMapper().fromJson(this.redisTemplate.boundValueOps(token).get(), User.class);
        if (user == null) {
            return this.failed("请登录后提交请假信息");
        }

        this.replaceCardServiceImpl.save(car);

        ReplaceCardApprovalRecords rcap = new ReplaceCardApprovalRecords();
        rcap.setReplaceCardId(car.getId());

        if (StringUtils.equals(user.getId(), car.getUserId())) {
            String parentUserId = this.userServiceImpl.getParentUser(user.getId()).getId();
            rcap.setUserId(parentUserId);
            rcap.setResult(0);
        } else {
            rcap.setUserId(user.getId());
            rcap.setResult(1);
        }

        return this.success(this.replaceCardApprovalRecordsServiceImpl.save(rcap));
    }

    /**
     * 补卡审批
     * 
     * @param rcap
     * @return
     */
    @GetMapping
    public R<Boolean> update(ReplaceCardApprovalRecords rcap) {
        if (rcap.getResult().equals(1)) {
            ReplaceCardApprovalRecords detail = this.replaceCardApprovalRecordsServiceImpl.getById(rcap.getId());
            ReplaceCard rc = this.replaceCardServiceImpl.getById(detail.getReplaceCardId());

            ClockIn clock = new ClockIn();
            clock.setUserId(rc.getId());
            clock.setWorkDay(rc.getCardTime().substring(0, 10));

            String cardTime = rc.getCardTime();
            if ("12:00".compareTo(rc.getCardTime().substring(11)) < 0) {
                clock.setWorkShift(cardTime);
            } else {
                clock.setClosingTime(cardTime);
            }

            this.clockInServiceImpl.update(clock,
                new QueryWrapper<ClockIn>().eq("work_day", clock.getWorkDay()).eq("user_id", rc.getUserId()));
        }

        rcap.setApprovalTime(LocalDateTime.now());

        return this.success(this.replaceCardApprovalRecordsServiceImpl.updateById(rcap));
    }

    @GetMapping("/list/{ids}")
    public R<Boolean> updateList(@PathVariable String[] ids) {

        Collection<ReplaceCardApprovalRecords> listByIds =
            this.replaceCardApprovalRecordsServiceImpl.listByIds(Arrays.asList(ids));
        listByIds.forEach(rcr -> {
            rcr.setReason("正常");
            rcr.setResult(2);
            rcr.setApprovalTime(LocalDateTime.now());

            ReplaceCardApprovalRecords detail = this.replaceCardApprovalRecordsServiceImpl.getById(rcr.getId());
            ReplaceCard rc = this.replaceCardServiceImpl.getById(detail.getReplaceCardId());

            ClockIn clock = new ClockIn();
            clock.setUserId(rc.getId());
            clock.setWorkDay(rc.getCardTime().substring(0, 10));

            String cardTime = rc.getCardTime();
            if ("12:00".compareTo(rc.getCardTime().substring(11)) < 0) {
                clock.setWorkShift(cardTime);
            } else {
                clock.setClosingTime(cardTime);
            }

            this.clockInServiceImpl.update(clock,
                new QueryWrapper<ClockIn>().eq("work_day", clock.getWorkDay()).eq("user_id", rc.getUserId()));
            rcr.setApprovalTime(LocalDateTime.now());
        });

        return this.success(this.replaceCardApprovalRecordsServiceImpl.updateBatchById(listByIds));
    }

    /**
     * 补卡申请审批
     * 
     * @param token
     * @return
     */
    @GetMapping("/approve")
    public R<List<ReplaceCardVO>> getApprove(@RequestHeader(value = "token") String token) {
        User user = JsonMapper.nonDefaultMapper().fromJson(this.redisTemplate.boundValueOps(token).get(), User.class);
        return this.success(this.replaceCardServiceImpl.getApprove(user.getId()));
    }

    /**
     * 补卡申请详情
     * 
     * @param replaceCardRecordId
     * @return
     */
    @GetMapping("/detail")
    public R<ReplaceCardVO> getApproveDetail(String replaceCardRecordId) {
        return this.success(this.replaceCardServiceImpl.getApproveDetail(replaceCardRecordId));
    }

    /**
     * 汇总人员的补卡次数
     * 
     * @param userId
     * @return
     */
    @GetMapping("/count/patchcard")
    public R<Integer> countPatchCard(String userId) {
        return this.success(this.replaceCardServiceImpl.count(new QueryWrapper<ReplaceCard>().eq("user_id", userId)));
    }

    /**
     * 分页查询补卡说明
     * 
     * @param page
     * @return
     */
    @GetMapping("/page")
    public R<IPage<ReplaceCardVO>> page(Page<ReplaceCardVO> page, CommonQuery commonQuery, Integer result,
        @RequestHeader("token") String token) {
        String userId = this.userServiceImpl.getLoginUser(token).getId();
        commonQuery.setUserId(userId);
        return this.replaceCardServiceImpl.page(page, commonQuery, result);
    }

}
